package com.msmall.community.album.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.pager.PaginationSupport;
import com.msmall.base.service.impl.BaseManagerImpl;
import com.msmall.base.util.ConstantDB;
import com.msmall.base.util.Constants;
import com.msmall.community.album.dao.AlbumDao;
import com.msmall.community.album.model.Album;
import com.msmall.community.album.model.Photo;
import com.msmall.community.album.model.Reply;
import com.msmall.community.album.service.AlbumManager;
import com.msmall.community.album.util.AlbumUtil;
import com.msmall.community.album.vo.ReplyVO;
import com.msmall.community.common.util.FilterCharsUtil;
import com.msmall.community.question.util.QuestionUtil;
import com.msmall.community.user.service.UserManager;

public class AlbumManagerImpl extends BaseManagerImpl implements AlbumManager {

	private static final Log logger = LogFactory.getLog(AlbumManagerImpl.class);
	
	private AlbumDao albumDao;
	
	private UserManager userManager;

	public void setAlbumDao(AlbumDao albumDao) {
		this.albumDao = albumDao;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	/**
	 * 用户创建相册
	 */
	public void saveAlbum(Album album, Long userid) throws Exception{
		try{
			album.setCreateTime(new Date());
			album.setLastModifyTime(album.getCreateTime());
			album.setUserid(userid);
			if(album.getLockStatus() == null){
				album.setLockStatus(ConstantDB.UNLOCK_STATUS);
				album.setPassword(null);
			}
			album.setCounts(0);
			albumDao.saveObject(album);
			
			userManager.addAlbumAmount(userid);
		}catch(Exception e){
			logger.error(e);
			throw e;
		}
	}
	
	/**
	 * 删除相册
	 * @param albumid 被删除的相册ID
	 * @param targetid 相片被移动到
	 */
	public void removeAlbum(Long albumid, Long targetid, Long userid) throws Exception{
		try{
			if(targetid != null){
				albumDao.updatePhotoAlbum(albumid, targetid, userid);
			}
			albumDao.remove(Album.class, albumid);
		}catch(Exception e){
			logger.error(e);
			throw e;
		}
	}
	/**
	 * 获得用户所有的相册列表
	 * @param userid
	 */
	public List<Album> getAlumsByUserid(Long userid) throws Exception{
		try{
			List<Album> list = new ArrayList<Album>();
			List<Object[]> rlt = albumDao.getAlumsByUserid(userid);
			if(rlt != null && rlt.size() > 0){
				Album a = null;
				Photo p = null;
				for(Object[] ap : rlt){
					a = (Album) ap[0];
					p = (Photo) ap[1];
					a.setPhoto(p);
					list.add(a);
				}
			}
			return list;
		}catch(Exception e){
			logger.error(e);
			throw e;
		}
	}
	/**
	 * 给相册设置封面
	 * @return
	 */
	public void setCover(Long albumid, Long photoid, Long userid) throws Exception{
		try{
			Album album = (Album) albumDao.get(Album.class, albumid);
			album.setPhotoid(photoid);
			albumDao.saveObject(album);
		}catch(Exception e){
			logger.error(e);
			throw e;
		}
	}
	/**
	 * 用户上传照片
	 */
	public void uploadImages(File[] images,String[] filenames, Long albumid, Long userid, Short reply, String uat) throws Exception{
		try{
			File image;
			String filename;
			String filenameChanged;
			String fileExt;
			String[] pathinfo;
			String[] fileSuf;
			Photo photo;
			for(int i=0;i<images.length; i++){
				image = images[i];
				filename = filenames[i];
				fileSuf = filename.split("\\.");
				filenameChanged = fileSuf[0] + "_" + Calendar.getInstance().getTimeInMillis();
				fileExt = fileSuf[1];
				pathinfo = AlbumUtil.saveImage(image, filenameChanged + "."+fileExt, userid, uat);
				
				
				photo = new Photo();
				photo.setAlbumid(albumid);
				photo.setCreateTime(new Date());
				photo.setFilePath(pathinfo[0]);
				photo.setFileName(filenameChanged);
				photo.setFileExt(fileExt);
				photo.setReply(reply);
				photo.setTitle("");
				photo.setUserid(userid);
				photo.setClickAmount(0);
				photo.setTopAmount(0);
				photo.setReplyAmount(0);
				albumDao.saveObject(photo);
			}
			
			Album album = (Album) albumDao.get(Album.class, albumid);
			album.setCounts(album.getCounts() + images.length);
			album.setLastModifyTime(new Date());
			albumDao.saveObject(album);
		}catch(Exception e){
			log.error(e);
		}
	}
	
	/**
	 * 通过id查找照片，同时增加图片访问次数
	 */
	public Photo getPhotoByid(Long photoid) throws Exception{
		try{
			Photo photo = (Photo) albumDao.get(Photo.class, photoid);
//			photo.setClickAmount(photo.getClickAmount() + 1);
//			albumDao.saveObject(photo);
			return photo;
		}catch(Exception e){
			log.error(e);
			throw e;
		}
	}
	/**
	 * 通过id查找照片的前一张图片,按ID排序，如果是第一张，跳到最后一张，同时增加图片访问次数
	 */
	public Photo getPhotoPreByid(Long photoid) throws Exception{
		try{
			Photo p = albumDao.getPhotoPreByid(photoid);
			if(p != null){
				return p;
			}else{
				PaginationSupport page = new PaginationSupport();
				StringBuffer buffer = new StringBuffer();
				buffer.append("select a from Photo a")
				.append(" WHERE a.albumid=(select b.albumid FROM Photo b where b.photoid=").append(photoid)
				.append(") AND a.photoid !=").append(photoid)
				.append(" ORDER BY a.photoid DESC");
				page.setQueryString(buffer.toString());
				page.setAutoCount(false);
				page.setPageSize(1);
				albumDao.getPagination(page);
				List list = page.getItems();
				if(list != null && list.size() > 0)
					return (Photo) list.get(0);
				else
					return null;
			}
		}catch(Exception e){
			log.error(e);
			throw e;
		}
	}
	/**
	 * 通过id查找照片的后一张图片,按ID排序，如果是最后一张，跳到第一张，同时增加图片访问次数
	 */
	public Photo getPhotoNextByid(Long photoid) throws Exception{
		try{
			Photo p = albumDao.getPhotoNextByid(photoid);
			if(p != null){
				return p;
			}else{
				PaginationSupport page = new PaginationSupport();
				StringBuffer buffer = new StringBuffer();
				buffer.append("select a from Photo a")
				.append(" WHERE a.albumid=(select b.albumid FROM Photo b where b.photoid=").append(photoid)
				.append(") AND a.photoid !=").append(photoid)
				.append(" ORDER BY a.photoid ASC");
				page.setQueryString(buffer.toString());
				page.setAutoCount(false);
				page.setPageSize(1);
				albumDao.getPagination(page);
				List list = page.getItems();
				if(list != null && list.size() >0){
					return (Photo) list.get(0);
				}else{
					return null;
				}
			}
		}catch(Exception e){
			log.error(e);
			throw e;
		}
	}
	/**
	/**
	 * 分页显示一个相册下的相片
	 */
	public void albumList(PaginationSupport page, Long userid, Long albumid) throws Exception{
		try{
			page.setPageSize(AlbumUtil.ALBUM_PHOTO_LIST_PAGESIZE_DEFAULT);
			String sql = "SELECT p FROM Photo p, Album a WHERE a.albumid=" 
					+albumid 
					+" and p.albumid=a.albumid";
			page.setQueryString(sql);
			page.setAutoCount(false);
			albumDao.getPagination(page);
			
			Album album = (Album) albumDao.get(Album.class, albumid);
			page.setTotalCount(album.getCounts());
		}catch(Exception e){
			log.error(e);
		}
	}
	/**
	 * 访客(userid)进入加密相册时，验证密码<br/>
	 * @return
	 */
	public boolean valid(Long albumid, Long userid, String password) throws Exception{
		try{
			Album album = (Album) albumDao.get(Album.class, albumid);
			if(ConstantDB.LOCK_STATUS.compareTo(album.getLockStatus()) == 0
				&& album.getPassword().equals(password)){
				return true;
			}
		}catch(Exception e){
			log.error(e);
		}
		return false;
	}
	
	/**
	 * 获得图片的所有评论.盖楼效果
	 */
	public List<ReplyVO> getReplysByPhotoid(Long photoid, Short enabled)throws Exception{
		List<ReplyVO> rlt = new ArrayList<ReplyVO>();
		List<Reply> list = albumDao.getReplysByPhotoid(photoid, enabled);
		if(list != null && list.size() > 0){
			Reply reply;
			ReplyVO vo;
			ReplyVO parentvo;
			Long parentid;
			Map<Long,ReplyVO> mapvos = new HashMap<Long,ReplyVO>();
			for(int i=0;i<list.size(); i++){
				reply = list.get(i);
				vo = new ReplyVO();
				vo.setReply(reply);
				mapvos.put(reply.getReplyid(), vo);
			}
			for(int i=0;i<list.size(); i++){
				reply = list.get(i);
				vo = mapvos.get(reply.getReplyid());
				parentid = reply.getParentid();
				parentvo = mapvos.get(parentid);
				if(parentid != null && parentid >0){
					parentvo.setNext(vo);
				}else{
					rlt.add(vo);
				}
			}
			List<ReplyVO> subs;
			ReplyVO next;
			for(int i=0;i<rlt.size();i++){
				vo = rlt.get(i);
				next = vo.getNext();
				if(next != null){
					subs = new ArrayList<ReplyVO>();
					vo.setSubs(subs);
					while(next != null){
						subs.add(next);
						next = next.getNext();
					}
				}
			}
		}
		return rlt;
	}
	
	/**
	 * 验证Photo.reply content
	 * @return 1:正常；2字符太少；3字符太多;4含有非法字符
	 */
	public int validateReplyContent(String content){
		int titleOK = QuestionUtil.checkQuestionAnswerLength(content);
		if(titleOK == 2){
			return 2;
		}
		if(titleOK == 3){
			return 3;
		}
		boolean titleC = FilterCharsUtil.containsFilterChars(content);
		if(titleC){
			return 4;
		}
		return 1;
	}
	/**
	 * 同时增加图片评论回答数量
	 */
	public Reply savePhotoReply(Reply reply, Long userid, String uat) throws Exception{
		try{
			reply.setCreateTime(new Date());
			reply.setUserid(userid);
			reply.setEnabled(ConstantDB.AVALIABLE);
			reply.setSource(Constants.USER_AGENT_TYPE_WML.equalsIgnoreCase(uat)? ConstantDB.USER_AGENT_TYPE_WML :ConstantDB.USER_AGENT_TYPE_HTML);
			reply = (Reply) albumDao.saveObject(reply);
			
			Photo photo = (Photo) albumDao.get(Photo.class, reply.getPhotoid());
			photo.setReplyAmount(photo.getReplyAmount() +1 );
			
			photo = (Photo) albumDao.saveObject(photo);
			return reply;
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
}
